<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表渲染--过滤与排序</title>
</head>
<body>
<!--
    1/列表过滤
    2/列表排序
-->

<div id="test">
    <input type="text" v-model="searchName">
    <ul>
        <li v-for="(p,index) in filterPersons" :key="index">
            {{index}} -- {{p.name}}--{{p.age}}
        </li>
    </ul>

    <button @click="setOrderType(1)">年龄升序</button>
    <button @click="setOrderType(2)">年龄降序</button>
    <button @click="setOrderType(0)">原本升序</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    const vm = new Vue({
        el:'#test',
        data:{
            searchName:'',
            orderType:0, /*0代表原本顺序，1代表升序，2代表降序*/
            persons:[
                {name:'Tom',age:18},
                {name:'Jerry',age:20},
                {name:'Army',age:15},
                {name:'kof',age:30},
                {name:'coff',age:21},
            ]
        },
        methods:{
            setOrderType(orderType){
                this.orderType = orderType;
            }
        },
        computed:{
            /*过滤计算*/
            filterPersons(){
                /*取出相关的数据*/
                const {searchName,persons} = this;
                /*最终需要显示的数组*/
                let fPersons;
                /*对persons进行过滤*/
                fPersons = persons.filter(p => p.name.indexOf(searchName) !== -1);

                let orderType = this.orderType;
                /*对数组进行排序*/
                if (orderType !== 0){
                    fPersons.sort(function (p1,p2) { /*这里不能写this.orderType因为在这个方法里，this不再是外部的this*/
                        if (orderType === 1){ /*可以理解成true的时候不换位，false换位*/
                            return p1.age - p2.age;
                        }else {
                            return p2.age - p1.age;
                        }
                    })
                }

                return fPersons;

                /*/!*请帮我看看这里有什么问题👀*!/
                return this.persons.filter(function (value) {
                    if (value.name.indexOf(value) !== -1) return value;
                });*/
            }
        }
    })
</script>
</body>
</html>